<template>
  <div>
    <v-row class="row-wrap">
      <v-col class="d-flex flex-column justify-center pl-5 pr-10" clos="12" md="6" sm="6">
        <div class="text-h5 font-weight-bold default--text text-capitalize">
          {{ $t("Page.Swap.HotTrade") }}
        </div>
        <div class="mt-5">
          <v-btn outlined small color="#AC8250" v-for="(item, index) in pairs" :key="index"
            class="px-2 rounded-pill mb-2 mr-4" @click="selectFromPair(item)">{{ item.pair }}</v-btn>
        </div>
        <!-- <a href="https://link.medium.com/34V6QCoLyyb" target="_blank"><img v-if="newsil8n=='zh'" width="100%" class="mt-15 rounded-lg" src="../assets/images/png/swapzh.png" /></a>
        <a href="https://link.medium.com/SFjQM9kLyyb" target="_blank"><img v-if="newsil8n=='ja'" width="100%" class="mt-15 rounded-lg" src="../assets/images/png/swapja.png" /></a>
        <a href="https://link.medium.com/HlY0OqGxByb" target="_blank"><img  v-if="newsil8n=='en'" width="100%" class="mt-15 rounded-lg" src="../assets/images/png/swapen.png" /></a> -->
        <v-carousel cycle hide-delimiter-background hide-delimiters show-arrows-on-hover height="150" class="mt-15">
          <v-carousel-item>
            <v-sheet height="100%">
              <v-row class="fill-height" align="center" justify="center">
                <a href="https://link.medium.com/34V6QCoLyyb" target="_blank"><img v-if="newsil8n == 'zh'" width="100%"
                    class="rounded-lg" src="../assets/images/png/swapzh.png" /></a>
                <a href="https://link.medium.com/SFjQM9kLyyb" target="_blank"><img v-if="newsil8n == 'ja'" width="100%"
                    class="rounded-lg" src="../assets/images/png/swapja.png" /></a>
                <a href="https://link.medium.com/HlY0OqGxByb" target="_blank"><img v-if="newsil8n == 'en'" width="100%"
                    class="rounded-lg" src="../assets/images/png/swapen.png" /></a>
              </v-row>
            </v-sheet>
          </v-carousel-item>
          <v-carousel-item>
            <v-sheet height="100%">
              <v-row class="fill-height" align="center" justify="center">
                <a href="https://link.medium.com/tyCsP7TiSyb" target="_blank"><img v-if="newsil8n == 'zh'" width="100%"
                    class="rounded-lg" src="../assets/images/png/swapzh2.png" /></a>
                <a href="https://link.medium.com/s4dIAx7fSyb" target="_blank"><img v-if="newsil8n == 'ja'" width="100%"
                    class="rounded-lg" src="../assets/images/png/swapja2.png" /></a>
                <a href=" https://link.medium.com/QZy8ByLeSyb" target="_blank"><img v-if="newsil8n == 'en'" width="100%"
                    class="rounded-lg" src="../assets/images/png/swapen2.png" /></a>

                <a href="https://link.medium.com/s4dIAx7fSyb" target="_blank"><img v-if="newsil8n == 'kr'" width="100%"
                    class="rounded-lg" src="../assets/images/png/swapja2.png" /></a>

              </v-row>
            </v-sheet>
          </v-carousel-item>
        </v-carousel>
      </v-col>

      <v-col class="pl-10" cols="12" md="6" sm="6">
        <v-card class="pa-5">
          <div class="d-flex justify-space-between align-center">
            <div class="default--text font-20 font-weight-medium">{{ $t("Menu.Swap") }}</div>
          </div>

          <div class="d-flex justify-end text-caption mt-8">
            <div class="default--text ml-4">
              <span class="text-caption grey--text mr-1">{{ $t("Page.Swap.Balance") }}:</span>
              <span class="text-body-2 primary--text font-weight-bold">{{ balance }}</span>
              <span class="text-caption grey--text ml-1">{{ fromPair.from }}</span>
            </div>
          </div>

          <div class="border radius d-flex justify-space-between align-center pr-2 mt-2">
            <div class="d-flex justify-start align-center" style="height: 56px; cursor: pointer">
              <v-menu min-width="240" offset-y close-delay="200" v-if="fromPair">
                <template v-slot:activator="{ on, attrs }">
                  <div class="d-flex justify-space-between align-center pl-2" v-bind="attrs" v-on="on"
                    style="cursor: pointer">
                    <div class="d-flex justify-start align-center" style="height: 56px; cursor: pointer">
                      <v-img contain width="24" height="24" :src="require('@/assets/images/svg/' + fromPair.fromIcon)"
                        class="rounded-circle"></v-img>
                      <div class="default--text text-body-2 font-weight-semibold ml-3">
                        {{ fromPair.from }}
                      </div>
                      <v-icon color="#AC8250" size="24">{{ icons.mdiMenuDown }}</v-icon>
                    </div>
                  </div>
                </template>
                <v-list style="border: 1px solid #ac8250; border-radius: 8px">
                  <v-list-item class="d-flex justify-start align-center cursor-pointer" v-for="(item, index) in pairs"
                    :key="index" @click="selectFromPair(item)" v-if="item.from !== fromPair.from">
                    <v-list-item-avatar>
                      <v-img contain width="24" height="24" :src="require('@/assets/images/svg/' + item.fromIcon)"
                        class="rounded-circle"></v-img>
                    </v-list-item-avatar>
                    <v-list-item-content>
                      <v-list-item-title class="text-body-2">{{ item.from }}</v-list-item-title>
                    </v-list-item-content>
                  </v-list-item>
                </v-list>
              </v-menu>
            </div>

            <div style="width: 100%">
              <v-text-field single-line hide-details autofocus v-model="amountFrom" type="number" step="0.1"
                :rules="[rules.required, rules.amount]" :disabled="pending" :max="amountMax"
                class="text-body-1 text-right theme-text mt-0 pt-0" @keyup="amountInputChange"
                @change="amountInputChange">
              </v-text-field>
            </div>
          </div>
          <div class="d-flex justify-center pointer my-2">
            <v-btn icon primary>
              <v-icon>{{ icons.mdiArrowDown }}</v-icon>
            </v-btn>
          </div>
          <div class="border radius d-flex justify-space-between align-center px-2 my-2">
            <div class="d-flex justify-start align-center" style="height: 56px; cursor: pointer">
              <v-img cover width="24" height="24" src="@/assets/images/svg/sct.svg" class="rounded-circle"></v-img>
              <div class="default--text text-body-2 ml-3 font-weight-semibold">SCT</div>
            </div>
            <div style="width: 100%">
              <v-text-field single-line hide-details autofocus v-model="amountTo" placeholder="200" type="number"
                step="1000" :rules="[rules.required, rules.amount]" disabled
                class="text-body-1 text-right theme-text mt-0 pt-0">
              </v-text-field>
            </div>
          </div>

          <div class="d-flex justify-space-between align-center px-2 my-4">
            <div v-if="price" class="text-caption">
              <span class="grey--text mr-1">{{ $t("Page.Swap.nowPrice") }}:</span>
              <span class="primary--text">1 {{ fromPair.from }}</span>
              <span class="grey--text mx-1">{{ $t("Page.Swap.canExchange") }}</span>
              <span class="primary--text">{{ readableNumber(this.price) }} SCT</span>
            </div>
          </div>

          <v-btn v-if="!ethAddress" color="primary" class="my-6 width-100" x-large depressed @click="connectWallet">
            {{ $t("Page.Wallet.Btn") }}
          </v-btn>
          <v-btn v-else-if="networkError" color="primary" class="color-fff my-6 width-100" x-large depressed
            @click="switchNet()">
            {{ $t("Page.Swap.SwitchTo") }}
            <span class="mx-2 font-weight-bold">{{ fromChain.name }}</span>
            {{ $t("Page.Swap.Network") }}
          </v-btn>
          <v-btn v-else-if="amountFrom > amountMax" disabled color="primary" class="color-fff my-6 width-100" x-large
            depressed>
            {{ $t("Page.Swap.InsBal") }}
          </v-btn>
          <v-btn v-else-if="ethAddress" :disabled="amountTo <= 0" class="color-fff my-6 width-100" x-large depressed
            color="primary" :loading="pending" @click="exchange">
            {{ $t("Page.Swap.Exchange") }}
          </v-btn>
        </v-card>
      </v-col>
    </v-row>

    <connect-wallet-dialog ref="connectWallet" />
  </div>
</template>

<script>
import { switchNetWork } from "@/utils/wallet";
import ConnectWalletDialog from "@/views/dialog/walletDialog.vue";
import {
  mdiArrowRight,
  mdiCreditCardClock,
  mdiArrowDown,
  mdiMenuDown,
  mdiReload,
  mdiCogOutline,
} from "@mdi/js";
import { mapState } from "vuex";
const numeral = require("numeral");
import SDK, { conNames, fromWei, toWei } from "@webfans/supercell";

export default {
  components: {
    ConnectWalletDialog,
  },
  data() {
    var pairs = [
      {
        pair: "USDT/SCT",
        from: "USDT",
        to: "SCT",
        fromIcon: "usdt.svg",
        toIcon: "sct.svg",
      },
      {
        pair: "ETH/SCT",
        from: "ETH",
        to: "SCT",
        fromIcon: "eth.svg",
        toIcon: "sct.svg",
      },
      {
        pair: "BNB/SCT",
        from: "BNB",
        to: "SCT",
        fromIcon: "bnb.svg",
        toIcon: "sct.svg",
      },
      {
        pair: "BUSD/SCT",
        from: "BUSD",
        to: "SCT",
        fromIcon: "busd.svg",
        toIcon: "sct.svg",
      },
    ];

    var fromPair = pairs[0];

    return {
      icons: {
        mdiArrowDown,
        mdiArrowRight,
        mdiCreditCardClock,
        mdiMenuDown,
        mdiReload,
        mdiCogOutline,
      },
      fromChainId: null,
      fromChain: null,
      pairs: pairs,
      fromPair: fromPair,
      reloading: false,
      sdkobj: null,
      newsil8n: "zh",
      balance: 0,
      pending: false,
      amountFrom: 0,
      amountMax: 0,
      amountTo: 0,
      price: 0,
      rules: {
        required: value => !!value || "Required.",
        amount: function (value) {
          value = parseFloat(value);
          if (value > this.amountMax) {
            console.log("Insufficient balance");
            return "Insufficient balance";
          }
          return true;
        }.bind(this),
      },
    };
  },
  computed: {
    ...mapState(["ethAddress", "ethChainID", "networkError", "ethersprovider", "GlobalConfig"]),
    isReady() {
      return this.ethChainID && this.ethAddress;
    },
  },
  watch: {
    isReady() {
      return this.ethChainID && this.ethAddress;
    },
    isReady() {
      this.reload();
    },
    ethAddress() {
      this.reload();
    },
    ethersprovider() {
      if (this.ethAddress) {
        this.getBalance();
      }
    },
    fromPair: function (val, oldVal) {
      this.reload();
    },
    "$i18n.locale"(newil8n) {
      this.newsil8n = newil8n;
    },
  },
  mounted() {
    this.newsil8n = this.$i18n.locale;
    setTimeout(() => {
      this.reload();
    }, 10);
  },
  methods: {
    async reload() {
      if (this.reloading) return;

      this.reloading = true;
      if (this.ethChainID == this.GlobalConfig.Swap.fromChainIdMainmet) {
        this.fromChainId = this.GlobalConfig.Swap.fromChainIdMainmet;
      } else if (this.ethChainID == this.GlobalConfig.Swap.fromChainId) {
        this.fromChainId = this.GlobalConfig.Swap.fromChainId;
      }
      this.fromChain = this.GlobalConfig.ChainList.find(item => item.chainId == this.fromChainId);

      await this.prepairData();
      this.reloading = false;
    },

    prepairData() {
      const networkNotMatch = this.fromChainId != this.ethChainID;
      // console.log(networkNotMatch);
      // this.$store.commit('networkError', networkNotMatch)
      this.fee = 0;
      this.balance = 0;
      this.amountFrom = 0;
      this.amountMax = 0;
      this.amountTo = 0;
      this.price = 0;

      // if (networkNotMatch) {
      //     return
      // }

      if (this.ethAddress) {
        this.getBalance();
      }
    },

    selectFromPair(pair) {
      this.fromPair = pair;
    },
    async switchNet() {
      await switchNetWork(this, this.fromChainId).catch(e => {
        this.$q.error(e.message);
      });
    },

    async getSdk() {
      if (this.ethersprovider == null || !this.ethAddress) {
        return null;
      }
      let sdk = new SDK(this.ethersprovider, parseInt(this.fromChainId));
      if (this.fromChainId == this.GlobalConfig.Swap.fromChainIdMainmet) {
        sdk.setAddressConfig(this.GlobalConfig.ContractMainnet);
      } else if (this.fromChainId == this.GlobalConfig.Swap.fromChainId) {
        sdk.setAddressConfig(this.GlobalConfig.Contract);
      }
      sdk.setAccount(this.ethAddress);
      return sdk;
    },

    async getBalance() {
      var sdk = await this.getSdk();
      if (!sdk) {
        return;
      }

      let balanceInWei = "";
      let priceList = null;
      if (this.fromPair.from == "USDT") {
        balanceInWei = await sdk.getUSDTContract().getBalance();
        priceList = await sdk.getNucleusContract().usdtAndSctPrise(conNames.USDT, conNames.SCT);
      } else if (this.fromPair.from == "BNB") {
        balanceInWei = await sdk.getNativeTokenBalance();
        priceList = await sdk.getNucleusContract().usdtAndSctPrise(conNames.BNB, conNames.SCT);
      } else if (this.fromPair.from == "ETH") {
        balanceInWei = await sdk.getETHContract().getBalance();
        priceList = await sdk.getNucleusContract().usdtAndSctPrise(conNames.ETH, conNames.SCT);
      } else if (this.fromPair.from == "BUSD") {
        balanceInWei = await sdk.getBUSDTContract().getBalance();
        priceList = await sdk.getNucleusContract().usdtAndSctPrise(conNames.BUSD, conNames.SCT);
      }

      let balance = fromWei(String(balanceInWei));
      this.amountMax = parseFloat(balance);
      this.balance = this.readableNumber(balance);

      if (priceList != null && priceList.length == 2) {
        this.price = priceList[0] / priceList[1];
      }
    },
    readableNumber(num) {
      const res = numeral(num).format("0,0#[.]0000");
      return res == "NaN" ? "0" : res;
    },
    connectWallet() {
      this.$refs.connectWallet.open();
    },

    async checkUSDTApprove(sdk, amount) {
      let haveAllonce = await sdk.getUSDTContract().allowanceNucleus(amount);
      if (haveAllonce) {
        return true;
      }

      let tx = await sdk
        .getUSDTContract()
        .approveNucleus()
        .catch(e => { });

      if (tx == null) {
        this.$q.error(this.$i18n.t("Page.Swap.ApprFail"));
        return false;
      }

      let txOk = await tx.wait().catch(e => {
        this.$q.error(e.message);
        return false;
      });

      if (!txOk) {
        return false;
      }

      haveAllonce = await sdk.getUSDTContract().allowanceNucleus(amount);
      return haveAllonce;
    },

    async checkBUSDApprove(sdk, amount) {
      let haveAllonce = await sdk.getBUSDTContract().allowanceNucleus(amount);
      if (haveAllonce) {
        return true;
      }

      let tx = await sdk
        .getBUSDTContract()
        .approveNucleus()
        .catch(e => { });

      if (tx == null) {
        this.$q.error(this.$i18n.t("Page.Swap.ApprFail"));
        return false;
      }

      let txOk = await tx.wait().catch(e => {
        this.$q.error(e.message);
        return false;
      });

      if (!txOk) {
        return false;
      }

      haveAllonce = await sdk.getBUSDTContract().allowanceNucleus(amount);
      return haveAllonce;
    },

    async checkETHApprove(sdk, amount) {
      let haveAllonce = await sdk.getETHContract().allowanceNucleus(amount);
      if (haveAllonce) {
        return true;
      }

      let tx = await sdk
        .getETHContract()
        .approveNucleus()
        .catch(e => { });

      if (tx == null) {
        this.$q.error(this.$i18n.t("Page.Swap.ApprFail"));
        return false;
      }

      let txOk = await tx.wait().catch(e => {
        this.$q.error(e.message);
        return false;
      });

      if (!txOk) {
        return false;
      }

      haveAllonce = await sdk.getETHContract().allowanceNucleus(amount);
      return haveAllonce;
    },

    async exchange() {
      var sdk = await this.getSdk();
      if (!sdk) {
        return;
      }

      this.pending = true;

      let fromToken = null;
      let haveAllonce = false;
      console.log(String(this.amountFrom));
      switch (this.fromPair.from) {
        case "USDT":
          fromToken = conNames.USDT;
          haveAllonce = await this.checkUSDTApprove(sdk, String(this.amountFrom));
          if (!haveAllonce) {
            this.pending = false;
            return;
          }
          break;
        case "BNB":
          fromToken = conNames.BNB;
          break;
        case "ETH":
          fromToken = conNames.ETH;
          haveAllonce = await this.checkETHApprove(sdk, String(this.amountFrom));
          if (!haveAllonce) {
            this.pending = false;
            return;
          }
          break;
        case "BUSD":
          fromToken = conNames.BUSD;
          haveAllonce = await this.checkBUSDApprove(sdk, String(this.amountFrom));
          break;
      }

      await sdk
        .getNucleusContract()
        .claim(fromToken, toWei(String(this.amountTo)))
        .then(async res => {
          await res
            .wait()
            .then(async receipt => {
              this.$q.success(this.$i18n.t("Page.Swap.SwapOK"));
              this.amountFrom = 0;
              this.amountTo = 0;
              this.getBalance();
            })
            .catch(e => {
              this.$q.error(e.message);
            });
        })
        .catch(e => {
          this.$q.error(e.message);
        });

      this.pending = false;
    },

    amountInputChange() {
      //make sure amountFrom is number
      if (this.amountFrom == null || this.amountFrom == "") {
        this.amountFrom = 0;
        this.amountTo = 0;
      } else {
        //如果是大于10的数字，又是以0开头的，那么就去掉0
        if (this.amountFrom != 0) {
          this.amountFrom = parseFloat(this.amountFrom);
        }

        if (this.amountFrom > this.amountMax) {
          this.amountFrom = this.amountMax;
        }

        this.amountTo = this.amountFrom * this.price;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.input-wrap {
  position: relative;

  .btn-wrap {
    position: absolute;
    right: 10px;
    top: 10px;
  }
}

.theme--light.v-sheet {
  background: none !important;
}

.theme--light.v-btn.v-btn--disabled.v-btn--has-bg {
  background-color: #70675b !important;
  color: #fff !important;
}

.theme-text {
  color: #ac8250 !important;
}
</style>

<style>
.theme--dark.v-input.theme-text input,
.theme--light.v-input.theme-text input {
  color: #ac8250 !important;
  text-align: right;
}

.v-text-field>.v-input__control>.v-input__slot:before,
.v-text-field>.v-input__control>.v-input__slot:after {
  display: none;
}
</style>
